// routes/airQuality.js
//主路由文件
const express = require('express');
const router = express.Router();
const redis = require('../clients/redis');
const OWMClient = require('../clients/owmClient');
const AQICNClient = require('../clients/aqicnClient');
const { validateCoordinates } = require('../utils/geoValidator');

const validateGeoParams = require('../middleware/validateGeoParams');

const owm = new OWMClient(process.env.OWM_API_KEY);
const aqicn = new AQICNClient(process.env.AQICN_TOKEN);

// 限流配置
const RateLimiterRedis = require('rate-limiter-flexible').RateLimiterRedis;
const rateLimiter = new RateLimiterRedis({
  storeClient: redis,
  points: 100, // 每分钟100次请求
  duration: 60 
});

// 定义 fetchAirQualityData 中间件
const fetchAirQualityData = async (req, res, next) => {
  try {
    const { lat, lon } = req.query;
    const [owmData, aqicnData] = await Promise.all([
      owm.getAirQuality(lat, lon),
      aqicn.getAirQuality(lat, lon)
    ]);
    req.airQualityData = { owm: owmData, aqicn: aqicnData };
    next();
  } catch (error) {
    next(error);
  }
};

// 定义 handleResponse 中间件
const handleResponse = (req, res) => {
  const cacheKey = `airQuality:${req.query.lat},${req.query.lon}`;
  redis.setex(cacheKey, 3600, JSON.stringify(req.airQualityData)); // 缓存1小时
  res.json(req.airQualityData);
};

// 修改 checkCache 中间件
const checkCache = (req, res, next) => {
  const cacheKey = `airQuality:${req.query.lat},${req.query.lon}`;
  redis.get(cacheKey, (err, data) => {
    if (err) {
      console.error('Redis connection error:', err); // 记录更详细的错误日志
      if (err.code === 'ENOTFOUND') {
        return res.status(500).json({ 
          error: 'Internal Server Error', 
          message: 'Failed to connect to Redis: Host not found' 
        });
      }
      return next(err);
    }
    if (data) {
      return res.json(JSON.parse(data));
    }
    next();
  });
};

// 修改 applyRateLimiting 中间件
const applyRateLimiting = (req, res, next) => {
  rateLimiter.consume(req.ip)
    .then(() => {
      next();
    })
    .catch((err) => {
      console.error('Rate limit exceeded for IP:', req.ip); // 记录限流日志
      if (err.code === 'ENOTFOUND') {
        return res.status(500).json({ 
          error: 'Internal Server Error', 
          message: 'Failed to connect to Redis: Host not found' 
        });
      }
      res.status(429).json({ error: 'Too Many Requests', details: 'Please try again later.' });
    });
};

// 中间件链
// 添加这行导入语句

router.get('/',
  validateGeoParams,
  applyRateLimiting,
  checkCache,
  fetchAirQualityData,
  handleResponse
);

module.exports = router;